/**
 * 1.npm install vue --save
 */
import router from '@/router/index'
import axios from 'axios'
import {getToken} from "./auth";
import store from '@/store'
import {Message, Notification, MessageBox} from 'element-ui'

//设置BaseURL
axios.defaults.baseURL = "http://localhost:8080/api"

// request拦截器
axios.interceptors.request.use(config => {
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    if (getToken() && !isToken) {
        config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // get请求映射params参数（数组，null，undefined等数据设置）
    if (config.method === 'get' && config.params) {
        let url = config.url + '?'
        for (const propName of Object.keys(config.params)) {
            const value = config.params[propName]
            let part = encodeURIComponent(propName) + "="
            if (value !== null && typeof (value) !== "undefined") {
                if (typeof value === 'object') {
                    for (const key of Object.keys(value)) {
                        let params = propName + '[' + key + ']'
                        let subPart = encodeURIComponent(params) + "="
                        url += subPart + encodeURIComponent(value[key]) + "&"
                    }
                } else {
                    url += part + encodeURIComponent(value) + "&"
                }
            }
        }
        url = url.slice(0, -1)
        config.params = {}
        config.url = url
    }
    return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

//响应拦截器
axios.interceptors.response.use(
    res => {
        // 未设置状态码则默认成功状态
        const code = res.data.code || 200
        // 获取错误信息
        const msg = res.data.msg

        if (code === 401) {
            MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(() => {
                //退出登录
                store.dispatch('LogOut').then(() => {
                    let continueUrl = window.location.href
                    router.push({
                        path: `/login?continue_url=${continueUrl}`
                    })
                })
            })
        } else if (code === 403) {
            //没有权限
            router.push('/401')
        } else if (code === 404) {
            //没有资源
            router.push('/404')
        } else if (code === 500) {
            Message({
                message: msg,
                type: 'error'
            })
            return Promise.reject(new Error(msg))
        } else if (code !== 200) {
            Notification.error({
                title: msg
            })
            return Promise.reject('error')
        } else {
            return res.data
        }

        return res
    },
    error => {
        console.log('err' + error)
        let {message} = error
        if (message == "Network Error") {
            message = "后端接口连接异常"
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时"
        } else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常"
        }
        Message({
            message: message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)


/*
 * 封装请求方法
 */
const request = function (query) {
    return axios.request(query)
}

//post请求  ----> json格式的post请求
const post = function (url, params) {
    const query = {
        url: url,
        method: 'post',
        withCredentials: true, //跨域允许携带cookie
        timeout: 30000,
        data: params,
        headers: {'Content-Type': 'application/json', 'request-ajax': true, "isToken": true},
    }
    return request(query)
}

//post请求  ----> json格式的post请求 无需token
const postWithoutToken = function (url, params) {
    const query = {
        url: url,
        method: 'post',
        timeout: 30000,
        withCredentials: true, //跨域允许携带cookie
        data: params,
        headers: {'Content-Type': 'application/json', 'request-ajax': true, "isToken": false},
    }
    return request(query)
}

//put  ----> json格式的put请求
const put = function (url, params) {
    const query = {
        url: url,
        method: 'put',
        withCredentials: true, //跨域允许携带cookie
        timeout: 30000,
        data: params,
        headers: {'Content-Type': 'application/json', 'request-ajax': true, "isToken": true},
    }
    return request(query)
}


//delete  ----> json格式的delete请求
const del = function (url, params) {
    const query = {
        url: url,
        method: 'delete',
        withCredentials: true, //跨域允许携带cookie
        timeout: 30000,
        data: params,
        headers: {'Content-Type': 'application/json', 'request-ajax': true, "isToken": true},
    }
    return request(query)
}


//Get请求
const get = function (url, params) {
    const query = {
        url: url,
        method: 'get',
        withCredentials: true,
        timeout: 30000,
        params: params,
        headers: {'request-ajax': true, "isToken": true},
    }
    return request(query)
}

//Get请求 无需token
const getWithoutToken = function (url, params) {
    const query = {
        url: url,
        method: 'get',
        timeout: 30000,
        withCredentials: true, //跨域允许携带cookie
        params: params,
        headers: {'request-ajax': true, "isToken": false},
    }
    return request(query)
}

//post请求  ----> 表单格式的post请求
const form = function (url, params) {
    const query = {
        url: url,
        method: 'post',
        withCredentials: true,
        timeout: 30000,
        data: params,
        headers: {
            'Content-Type': 'multipart/form-data',
            'request-ajax': true,
            "isToken": true
        },
    }
    return request(query)
}

export {post, put, del, get, form, postWithoutToken, getWithoutToken}
